package videos;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import utility.Check_Net;
import utility.SDialog;
import utility.StreamUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.VideoView;
import example.demo_navi.R;

public class Procmain3 extends Activity{

	String str;
	VideoView vvd;
	String rtsp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.videoview);
		vvd=(VideoView) findViewById(R.id.vivi);
		Intent in=getIntent();
		str=in.getDataString();
		Log.d("tetproc", str);
		proan pr=new proan();
		if(Check_Net.isOnLine(Procmain3.this)){
			try{
		pr.execute();
			}catch(Exception ex){
				new Thread(new getyou3()).start();
			}
		}else{
			SDialog.Dialognet(Procmain3.this);
		}
	}

	private class getyou3 implements Runnable{

		public void run() {
			// TODO Auto-generated method stub
			Intent in=new Intent(Intent.ACTION_VIEW);
			try {
				in.setData(Uri.parse(getRstpLinks2(str)));
				startActivity(in);
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
	}
	
	private class proan extends AsyncTask<Void, Void, Void>{

		ProgressDialog pd;
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				rtsp=getRstpLinks(str);
				Log.d("KaKa", rtsp);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				
				e.printStackTrace();
			} 
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pd.dismiss();
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			try{
			vvd.setVideoURI(Uri.parse(rtsp));
			}catch(Exception ex){
				AlertDialog.Builder builder=new AlertDialog.Builder(Procmain3.this);
				builder.setTitle("Lỗi Phát Video");
				builder.setMessage("Bạn có thể tiếp tục hoặc chọn video khác- Thanks!");
				builder.setPositiveButton("Tiếp tục", new OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					new Thread(new getyou3()).start();
				
					}
				});
				builder.setNegativeButton("Trờ Lại", new OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if(Check_Net.isOnLine(Procmain3.this)){
						Intent in=new Intent(Procmain3.this, Main3.class);
						startActivity(in);
						}else{
							SDialog.Dialognet(Procmain3.this);
						}
					}
				});
				builder.show();
				Log.d("Bat Loi", ""+ex.getMessage());
			}
			 MediaController mc = new MediaController(Procmain3.this);
	          vvd.setMediaController(mc);
	          vvd.requestFocus();
	          vvd.start();  
	          
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pd=new ProgressDialog(Procmain3.this);
			pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			pd.setMessage("Loading video...");
			pd.show();
		}
		
	}
	
	private String getRstpLinks(String s) throws ClientProtocolException, IOException{
		String[] urls = new String[3];
	    HttpClient hc=new DefaultHttpClient();
		HttpUriRequest hr=new HttpGet(s+"&alt=json");
		HttpResponse hpon=hc.execute(hr);
		String js=StreamUtils.convertToString(hpon.getEntity().getContent());
	    try {
	        JSONObject obj = new JSONObject(js);
	        String entry = obj.getString("entry");
	        JSONObject enObj = new JSONObject(entry);
	        String group = enObj.getString("media$group");
	        JSONObject grObj = new JSONObject(group);
	        String content = grObj.getString("media$content");
	        String reli=grObj.getJSONObject("media$player").getString("url");
	        JSONArray array = grObj.getJSONArray("media$content");
	        for(int j=0; j<array.length(); j++){
	            JSONObject thumbs = array.getJSONObject(j);
	            String url = thumbs.getString("url");
	            urls[j] = url;
	            Log.d("Error_link", url);
	            //data.setThumbUrl(thumbUrl);
	        }


	        Log.v("Contento", content);
	    } catch (Exception e) {
	        Log.e("Getlink", e.toString());
	        SDialog.Dialoger(Procmain3.this);
	        urls[0] = urls[1] = urls[2] = null;
	    }
	    
	    return urls[2];      
	}
	
	private String getRstpLinks2(String s) throws ClientProtocolException, IOException{
		String[] urls = new String[3];
		String reli = null;
	    HttpClient hc=new DefaultHttpClient();
		HttpUriRequest hr=new HttpGet(s+"&alt=json");
		HttpResponse hpon=hc.execute(hr);
		String js=StreamUtils.convertToString(hpon.getEntity().getContent());
	    try {
	        JSONObject obj = new JSONObject(js);
	        String entry = obj.getString("entry");
	        JSONObject enObj = new JSONObject(entry);
	        String group = enObj.getString("media$group");
	        JSONObject grObj = new JSONObject(group);
	        String content = grObj.getString("media$content");
	        reli=grObj.getJSONObject("media$player").getString("url");
	        JSONArray array = grObj.getJSONArray("media$content");
	        for(int j=0; j<array.length(); j++){
	            JSONObject thumbs = array.getJSONObject(j);
	            String url = thumbs.getString("url");
	            urls[j] = url;
	            Log.d("Error_link", url);
	            //data.setThumbUrl(thumbUrl);
	        }


	        Log.v("Contento", content);
	    } catch (Exception e) {
	        Log.e("Getlink", e.toString());
	        
	        urls[0] = urls[1] = urls[2] = null;
	    }
	    
	    return reli;      
	}
}
